package RootDNSServer2;


import RootDNSServer2.MyClass.WaitReq;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Author: 0162977
 * @Date: 2020/12/3 15:43
 */
public class ShareSpaceAndFun {

    public static int myPort = 4031;
    public static int portTop = 4040;

    private static List<WaitReq> waitReqList = new ArrayList<WaitReq>();
    private static AtomicBoolean notify = new AtomicBoolean(false);

    public static boolean addWait(String website, int waitPort){

        while (!notify.compareAndSet(false,true)){;}
        for (int i = 0; i<waitReqList.size(); i++){
            if (waitReqList.get(i).getWebsite().equals(website)){
                if (waitReqList.get(i).getWaitPort().contains(waitPort)){

                    notify.set(false);
                    return false;
                }
                waitReqList.get(i).getWaitPort().add(waitPort);
                System.out.println(waitReqList);

                notify.set(false);
                return false;
            }
        }
        WaitReq waitReq = new WaitReq();
        waitReq.setWebsite(website);
        waitReq.setWaitPort(new ArrayList<Integer>() {{ add(waitPort); } });
        waitReq.setTimeStamp(new Date().getTime());

        waitReqList.add(waitReq);

        System.out.println(waitReqList);

        notify.set(false);
        return true;
    }
    public static List<Integer> getWaitPortByWebsite(String website){

        while (!notify.compareAndSet(false,true)){;}
        for (int i= 0; i< waitReqList.size(); i++){
            if (waitReqList.get(i).getWebsite().equals(website)){
                List<Integer> retList = waitReqList.get(i).getWaitPort();
                waitReqList.remove(i);
                System.out.println(waitReqList);

                notify.set(false);
                return retList;
            }
        }
        notify.set(false);
        return null;
    }
}
